package com.zsc.controller.user;

import com.zsc.constant.StatusConstant;
import com.zsc.dto.DishPageQueryDTO;
import com.zsc.result.PageResult;
import com.zsc.result.Result;
import com.zsc.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author
 * @Date 2024/6/13 18:51
 */

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "用户端 菜品浏览接口")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;



/*    public Result<List<Dish>> list(long categoryId) {
        // 构造redis中的key,规则：dish_分类id
        String key = "dish_" + categoryId;
        // 查询redis中是否存在菜品数据
        List<Dish> list = (List<Dish>) redisTemplate.opsForValue().get(key);
        if (list != null && !list.isEmpty()) {
            // 如果存在直接返回，无须查询数据库
            return Result.success(list);
        }
        list = dishService.listByCategoryId(categoryId);
        redisTemplate.opsForValue().set(key, list);
        return Result.success(list);
    }*/


    /**
     * 根据分类id查询菜品
     *
     * @param dishPageQueryDTO()
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id 分页查询菜品")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
        log.info("用户端菜品分页查询，查询参数：{}", dishPageQueryDTO);
        String key = "dish_" + dishPageQueryDTO.getCategoryId();
        PageResult pageResult = (PageResult) redisTemplate.opsForValue().get(key);
        if (pageResult != null && !pageResult.getRecords().isEmpty()) {
            // 如果存在直接返回，无须查询数据库
            return Result.success(pageResult);
        }
        dishPageQueryDTO.setStatus(StatusConstant.ENABLE);
        pageResult = dishService.pageQuery(dishPageQueryDTO);
        redisTemplate.opsForValue().set(key, pageResult);
        return Result.success(pageResult);
    }
}
